console.log("windows loaded");
var labels = {};
var all_labels = document.getElementsByTagName("label");
for (var i = 0; i < all_labels.length; i++) {
    if (all_labels[i].className == 'label-outside') {
        all_labels[i].className = 'label-inside';
    }
    labels[all_labels[i].getAttribute("for")] = all_labels[i];
}

function attachHandlers(input_id) {
var input = document.getElementById(input_id);
var label = labels[input_id];
input.onclick = function(e) {handleFirstClick(e, input, label);};
input.onkeyup = function(e) {handleKey(input, label);};
input.onblur = function(e) {handleBlur(e,input, label);};
    label.onclick = function(e) { 
        for (var l in labels) {
            if (label != labels[l] && labels[l].style.color == 'red') {
                var input = document.getElementById(l);
                    handleBlur(null,input, labels[l]);
            }
        }
        console.log("focusing"); 
        label.focused = true;
    };
    label.onblur = function(e) {label.focused = false;};
};
    
var attachInput = ["input1","input2"];
for (var j = 0; j < attachInput.length; j++) {
    attachHandlers(attachInput[j]);
}
};

function handleBlur(e, input, label) {
    console.log("blurring");
    if (!label.focused && (!input.value || input.value.length == 0)) {
        label.style.display = 'block';
        label.style.color = 'black';
        label.clickedBefore = false;
    }
    label.focused = false;
};

function handleFirstClick(e, input, label) {
    if (!label.clickedBefore) {
        label.clickedBefore = true;
        e.preventDefault();
        label.style.color = 'red';
    }
};

function handleKey(input, label) { 
    console.log("handling key up : " + input.value.length);
    label.style.display = 'none';
    if (!input.value || input.value.length == 0) {
        label.style.display = 'block';
        label.style.color = 'red';
    }      
};